package com.paipaideli.ui.mine.head;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.BuildConfig;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.photo.PhotoPopupWindow;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.PictureUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.CircleImageView;
import com.paipaideli.common.utils.OssFileUploadUtil;
import com.paipaideli.ui.mine.safety.event.LogoutEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 个人资料
 */
public class MyInfoActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.icon_info_image)
    CircleImageView icon_info_image;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.btn_tx)
    Button btn_tx;

//    PickView pickView;
//    //声明当前性别
//    String currentSex;
//    MyDialog mDialog;

    private PhotoPopupWindow mPhotoPopupWindow;
    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_SMALL_IMAGE_CUTTING = 2;
    private static final String IMAGE_FILE_NAME = "user_head_icon.jpg";

    @Override
    public int getContentView() {
        return R.layout.activity_myinfo;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("个人资料");

        //返回
        top_back.setOnClickListener(o ->
                finish()
        );
        String name = getIntent().getStringExtra("name");
        String image = getIntent().getStringExtra("image");
        if (!TextUtils.isEmpty(image)) {
            filePath = image;
            isfilePath = true;
            ImageUtil.displayImage(image, icon_info_image);
        }
        if (!TextUtils.isEmpty(name)) {
            et_title.setText(name);
            et_title.setSelection(name.length());//将光标移至文字末尾
        }

//        ll_info_sex.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                View views = View.inflate(MyInfoActivity.this, R.layout.info_dialog, null);
//                mDialog = new MyDialog(MyInfoActivity.this, views);
//                pickView = (PickView) view.findViewById(R.id.pvPickView);
//               //定义滚动选择器的数据项
//                ArrayList<String> grade = new ArrayList<>();
//                grade.add("保密");
//                grade.add("女");
//                grade.add("男");
//                //为滚动选择器设置数据
//                pickView.setData(grade);
//                pickView.setOnSelectListener(new PickView.onSelectListener() {
//                    @Override
//                    public void onSelect(String text) {
//                       ToastUtil.show(text);
//                        currentSex = text;
//                    }
//                });
//                mDialog.show();
//            }
//        });

        RxView.clicks(icon_info_image).subscribe(o -> {
            //创建存放头像的文件夹
            PictureUtil.mkdirMyPetRootDirectory();
            mPhotoPopupWindow = new PhotoPopupWindow(MyInfoActivity.this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 如果权限已经申请过，直接进行图片选择
                    mPhotoPopupWindow.dismiss();
                    // 文件权限申请
                    if (ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 权限还没有授予，进行申请
                        ActivityCompat.requestPermissions(MyInfoActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200); // 申请的 requestCode 为 200
                    } else {
                        // 如果权限已经申请过，直接进行图片选择
                        mPhotoPopupWindow.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        // 判断系统中是否有处理该 Intent 的 Activity
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(intent, REQUEST_IMAGE_GET);
                        } else {
                            ToastUtil.show("未找到图片查看器");
                        }
                    }
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 权限已经申请，直接拍照
                    mPhotoPopupWindow.dismiss();
                    // 拍照及文件权限申请
                    if (ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 权限还没有授予，进行申请
                        ActivityCompat.requestPermissions(MyInfoActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300); // 申请的 requestCode 为 300
                    } else {
                        // 权限已经申请，直接拍照
                        mPhotoPopupWindow.dismiss();
                        imageCapture();
                    }
                }
            });
            View rootView = LayoutInflater.from(MyInfoActivity.this).inflate(R.layout.fragment_home, null);
            mPhotoPopupWindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }, throwable -> {
            Log.d("TAG", "异常" + throwable.getMessage());
        });


        btn_tx.setOnClickListener(v -> {
            String trim = et_title.getText().toString().trim();
            if (TextUtils.isEmpty(filePath)) {
                ToastUtil.show("请添加头像");
                return;
            } else if (TextUtils.isEmpty(trim)) {
                ToastUtil.show("请填写用户名");
                return;
            }
            if (isfilePath) {
                JSONObject requestData = new JSONObject();
                try {
                    requestData.put("avatar", filePath);
                    requestData.put("username", et_title.getText().toString().trim());
                } catch (Exception e) {
                    e.getMessage();
                }
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                Api.getInstanceGson().update(body).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(onLoad -> {
                            if (onLoad.getCode().equals("200")) {
                                finish();
                                LogoutEvent logoutEvent = new LogoutEvent();
                                logoutEvent.setCheck(3);
                                EventBus.getDefault().post(logoutEvent);
                            } else {
                                ToastUtil.show(onLoad.getMessage());
                            }
                        }, throwable -> {
                        });
            } else {
                Observable.just(filePath)
                        .subscribeOn(Schedulers.io())
                        .map(path -> OssFileUploadUtil.uploadSync(path, OssFileUploadUtil.NameSpace.AVATAR))
                        .flatMap(request -> {
                            JSONObject requestData = new JSONObject();
                            try {
                                String url = BuildConfig.photo + request.getObjectKey();

                                requestData.put("avatar", url);
                                requestData.put("username", et_title.getText().toString().trim());
                            } catch (Exception e) {
                                e.getMessage();
                            }
                            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                            return Api.getInstanceGson().update(body);
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(onLoad -> {
                            if (onLoad.getCode().equals("200")) {
                                finish();
                            } else {
                                ToastUtil.show(onLoad.getMessage());
                            }
                        }, throwable -> {
                        });
            }
        });
    }

    String filePath;
    boolean isfilePath = false;

    //以下为头像相关方法
    private void showHeadImage() {
        boolean isSdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);// 判断sdcard是否存在
        if (isSdCardExist) {
            filePath = FastData.getHead_image();// 获取图片路径
            File file = new File(filePath);
            if (file.exists()) {
                isfilePath = false;
                Bitmap bm = BitmapFactory.decodeFile(filePath);
                // 将图片显示到ImageView中
                icon_info_image.setImageBitmap(bm);
            } else {
                isfilePath = false;
                Log.e(TAG, "no file");
                icon_info_image.setImageResource(R.mipmap.icon_yuan);
            }
        } else {
            isfilePath = false;
            Log.e(TAG, "no SD card");
            icon_info_image.setImageResource(R.mipmap.icon_yuan);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调成功
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 切割
                case REQUEST_SMALL_IMAGE_CUTTING:
                    Log.e(TAG, "before show");
                    File cropFile = new File(PictureUtil.getMyPetRootDirectory(), "crop.jpg");
                    Uri cropUri = Uri.fromFile(cropFile);
                    setPicToView(cropUri);
                    break;

                // 相册选取
                case REQUEST_IMAGE_GET:
                    Uri uri = PictureUtil.getImageUri(this, data);
                    startPhotoZoom(uri);
                    break;

                // 拍照
                case REQUEST_IMAGE_CAPTURE:
                    File pictureFile = new File(PictureUtil.getMyPetRootDirectory(), IMAGE_FILE_NAME);
                    Uri pictureUri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        pictureUri = FileProvider.getUriForFile(this, "com.paipaideli.fileprovider", pictureFile);
                        Log.e(TAG, "picURI=" + pictureUri.toString());
                    } else {
                        pictureUri = Uri.fromFile(pictureFile);
                    }
                    startPhotoZoom(pictureUri);
                    break;
                default:
            }
        } else {
            Log.e(TAG, "result = " + resultCode + ",request = " + requestCode);
        }
    }

    public void setPicToView(Uri uri) {
        if (uri != null) {
            Bitmap photo = null;
            try {
                photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 创建 smallIcon 文件夹
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dirFile = new File(PictureUtil.getMyPetRootDirectory(), "Icon");
                if (!dirFile.exists()) {
                    if (!dirFile.mkdirs()) {
                        Log.d(TAG, "in setPicToView->文件夹创建失败");
                    } else {
                        Log.d(TAG, "in setPicToView->文件夹创建成功");
                    }
                }
                File file = new File(dirFile, IMAGE_FILE_NAME);
                FastData.setHead_image(file.getPath());
                // 保存图片
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 在视图中显示图片
            showHeadImage();
        }
    }

    private void startPhotoZoom(Uri uri) {
        Log.d(TAG, "Uri = " + uri.toString());
        //保存裁剪后的图片
        File cropFile = new File(PictureUtil.getMyPetRootDirectory(), "crop.jpg");
        try {
            if (cropFile.exists()) {
                cropFile.delete();
                Log.e(TAG, "delete");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri cropUri;
        cropUri = Uri.fromFile(cropFile);

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); // 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300); // 输出图片大小
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        Log.e(TAG, "cropUri = " + cropUri.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, REQUEST_SMALL_IMAGE_CUTTING);
    }

    private void imageCapture() {
        Intent intent;
        Uri pictureUri;
        //getMyPetRootDirectory()得到的是Environment.getExternalStorageDirectory() + File.separator+"MyPet"
        //也就是我之前创建的存放头像的文件夹（目录）
        File pictureFile = new File(PictureUtil.getMyPetRootDirectory(), IMAGE_FILE_NAME);
        // 判断当前系统
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //这一句非常重要
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //""中的内容是随意的，但最好用package名.provider名的形式，清晰明了
            pictureUri = FileProvider.getUriForFile(this, "com.paipaideli.fileprovider", pictureFile);
        } else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(pictureFile);
        }
        // 去拍照,拍照的结果存到oictureUri对应的路径中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        Log.e(TAG, "before take photo" + pictureUri.toString());
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
}
